//
//  StatusViewModel.swift
//  weibobbaj
//
//  Created by Tiffany宝 on 16/4/20.
//  Copyright © 2016年 Tiffany. All rights reserved.

// HomeTableController

import UIKit
import SDWebImage

class StatusViewModel: NSObject {
    
    //记录一下
    //    var cellArray: [StatusModel]?
    var cellArray: [CellStatusViewModel]?
    //        {
    //
    //        didSet{
    //            //拿到数据就刷新界面
    ////            tableView.reloadData()
    //        }
    //    }
    
    //加载首页的数据
    func loadStatus(isPullup: Bool,finished:(isSuccess: Bool,count: Int) -> ()){
        
//        let url = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        var max_id: Int64 = 0
        var since_id: Int64 = 0
        if isPullup{
            //是上拉加载
            
            //            print(cellArray?.last)
            // ****** 需要取到当前数组里面最后一个元素的id
            max_id = cellArray?.last?.status?.id ?? 0
            
            if max_id != 0{
                max_id--
            }
            
        }else{
            
            //下拉刷新
            since_id = cellArray?.first?.status?.id ?? 0
            
        }
        
        //account? 所以直接这样写会报错
        //        let parameters = ["access_token":UserAccountViewModel.sharedViewModel.account?.access_token]
        
//        guard let account = UserAccountViewModel.sharedViewModel.account?.access_token else{
//            
//            return
//        }
        
//        let parameters = [
//            "access_token":account,
//            "max_id":"\(max_id)",
//            "since_id":"\(since_id)"]
        //        let parameters = ["access_token":account,"max_id":max_id]
        
        StatusDAL.loadData(max_id, since_id: since_id) { (dicts) -> () in
            
            guard let arr = dicts else{
               return finished(isSuccess: false, count: 0)
            }
//        }
//        
//        NetworkTools.sharedTools.request( urlString: url, parameters: parameters) { (responseObject, error) -> Void in
//            
//            if error != nil{
//                
//                print(error)
//                finished(isSuccess: false,count: 0)
//                return
//            }
//            
//            //打印请求的微博数据
//            //            print(responseObject)
//            
//            guard let dic = responseObject as? [String : AnyObject] else{
//                
//                print("字典格式错误")
//                finished(isSuccess: false,count: 0)
//                return
//            }
//            
//            guard let arr = dic["statuses"] as? [[String : AnyObject]] else{
//                
//                finished(isSuccess: false,count: 0)
//                return
//            }
//            
//            //StatusDAL测试
////            StatusDAL.cacheData(arr)
            
            
            //定义一个可变数组
            //            var statusArr = [StatusModel]()
            var tempArr = [CellStatusViewModel]()
            
            //------------------------ 这里比较搞 -------------------------
            
            //遍历数组
            for value in arr{
                
                //字典转模型
                let model = StatusModel(dic: value)
                //初始化一个 ViewModel
                let viewModel = CellStatusViewModel()
                //设置模型到 ViewModel 里面去
                viewModel.status = model
                
                tempArr.append(viewModel)
                
                
                //                print("---------------\(model)")
                
                //测试 转发的微博内容
                //                if model.retweeted_status != nil{
                //
                //                    print("=====\(model)")
                //                }
                //
            }
            
            //            print(tempArr)
            //            self.cellArray = tempArr
            
            // ****为了下面的强行解包,需要初始化一个空数组
            if self.cellArray == nil{
                
                //                self.cellArray = []
                self.cellArray = [CellStatusViewModel]()
            }
            
            //判断上拉加载 还是 下拉刷新
            if isPullup{
                
                self.cellArray = self.cellArray! + tempArr
                
            }else{
                
                self.cellArray = tempArr + self.cellArray!
            }
            
            //            finished(isSuccess: true)
            
            print("加载回来\(tempArr.count)条数据")
            
            //缓存单张图片
            self.cachSingleImage(tempArr,finished:finished)
        }
    }
    
    // MARK: - 缓存单张图片
    private func cachSingleImage(array: [CellStatusViewModel],finished:(isSuccess: Bool,count: Int) -> ()){
        
        let group = dispatch_group_create()
        
        //1.遍历判断图片数组是否为单张
        for value in array{
            
            //是取原创微博的图片还是转发微博的图片
            let originPic = value.status?.pic_urls
            let retweetPic = value.status?.retweeted_status?.pic_urls
            
            //取到图片数组(是原创微博 or 转发微博)
            let picUrls = (originPic == nil || originPic?.count == 0) ? retweetPic : originPic
            
            // 判断是否为单张 , 并取到单张的下载地址
            if picUrls?.count == 1{
                
                let urlString = picUrls?.first?.thumbnail_pic
                //放一个鸡蛋
                dispatch_group_enter(group)
                
                //2.去下载
                SDWebImageManager.sharedManager().downloadImageWithURL(NSURL(string: urlString ?? ""), options: [], progress: nil, completed: { (image, error, _, _, _) -> Void in
                    
                    //3.监听下载完成
                    //更新单张图片的配图视图大小
                    value.updateSingleImagePictureSize()
                    
                    //拿出一个鸡蛋
                    dispatch_group_leave(group)
                })
                
            }
            
        }
        //4.所有单张图片下载完成后的通知(回主界面刷新)
        dispatch_group_notify(group, dispatch_get_main_queue(), { () -> Void in
            
            //回调刷新界面
            finished(isSuccess: true,count: array.count)
            
        })
        
    }
}
